package xyz.xwls.bootadmin.component;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import xyz.xwls.bootadmin.common.CommonResult;
import xyz.xwls.bootadmin.common.ResultCode;
import xyz.xwls.bootadmin.sys.domain.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WZW
 * @date 2020/4/17
 */
public class BaseController {

    /**
     * 获取登录用户
     * @return 登录的用户
     */
    public User getUser(){
        return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /**
     * 获取登录的用户编号
     * @return 用户编号
     */
    public Long getUserId(){
        return getUser().getId();
    }

    /**
     * 获取参数校验时的错误信息
     * @param bindingResult 参数校验的错误信息
     * @return
     */
    protected CommonResult<?> getErrors(BindingResult bindingResult) {
        List<Map<Object, Object>> errors = bindingResult.getFieldErrors().stream().map(fieldError -> {
            Map<Object, Object> map = new HashMap<>(2);
            map.put("field", fieldError.getField());
            map.put("message", fieldError.getDefaultMessage());
            return map;
        }).collect(Collectors.toList());
        CommonResult<Object> result = CommonResult.failed(ResultCode.VALIDATE_FAILED);
        result.setData(errors);
        return result;
    }
}
